package com.example.literj.kt.internal.operators.single

import com.example.literj.kt.core.Single
import com.example.literj.kt.core.SingleObserver
import com.example.literj.kt.core.SingleSource
import com.example.literj.kt.disposables.Disposable
import com.example.literj.kt.internal.functions.Function
import java.util.*

class SingleMap<T, R>(
    private val source: SingleSource<out T>,
    private val mapper: Function<in T, out R>
) : Single<R>() {
    override fun subscribeActual(observer: SingleObserver<in R>) {
        source.subscribe(MapSingleObserver(observer, mapper))
    }

    internal class MapSingleObserver<T, R>(
        private val t: SingleObserver<in R>,
        private val mapper: Function<in T, out R>
    ) : SingleObserver<T> {
        override fun onSuccess(t: T) {
            val v: R
            try {
                v = Objects.requireNonNull(
                    mapper.apply(t),
                    "The mapper function returned a null value."
                )
            } catch (e: Throwable) {
                onError(e)
                return
            }
            this.t.onSuccess(v)
        }

        override fun onSubscribe(d: Disposable) {
            t.onSubscribe(d)
        }

        override fun onError(e: Throwable) {
            t.onError(e)
        }
    }
}